package com.tony.demo.ui.performance.xnyh.draw;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

import com.puhui.lib.utils.DMLog;
import com.tony.demo.R;
import com.tony.demo.ui.performance.xnyh.draw.bean.DroidCard;

import java.util.ArrayList;
import java.util.List;

public class DroidCardsView extends View {

    //图片与图片之间的间距
    private int mCardSpacing = 150;
    //图片与左侧距离的记录
    private int mCardLeft = 10;

    private List<DroidCard> mDroidCards = new ArrayList<DroidCard>();

    private Paint paint = new Paint();

    private boolean isOptimize = false;

    public DroidCardsView(Context context) {
        super(context);
        initCards();
    }

    public DroidCardsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initCards();
    }

    public void setOptimize(boolean isOptimize) {
        this.isOptimize = isOptimize;
    }

    /**
     * 初始化卡片集合
     */
    protected void initCards() {
        Resources res = getResources();
        mDroidCards.add(new DroidCard(res, R.mipmap.alex, mCardLeft));

        mCardLeft += mCardSpacing;
        mDroidCards.add(new DroidCard(res, R.mipmap.claire, mCardLeft));

        mCardLeft += mCardSpacing;
        mDroidCards.add(new DroidCard(res, R.mipmap.kathryn, mCardLeft));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (isOptimize) {
            for (int i = 0; i < mDroidCards.size() - 1; i++) {
                drawDroidCard(canvas, i);
            }

            DroidCard lastCard = mDroidCards.get(mDroidCards.size() - 1);
            canvas.drawBitmap(lastCard.bitmap, lastCard.x, 0f, paint);
        } else {
            for (DroidCard c : mDroidCards) {
                drawDroidCardBeforeOpt(canvas, c);
            }
        }

        //由于这里调用了invalidate,导致onDraw方法一直循环调用
        //7.0之后不要在onDraw方法里面调用该方法; 7.0之前在onLayout  onMeasure里也不要调用该方法
//        invalidate();
    }

    private void drawDroidCardBeforeOpt(Canvas canvas, DroidCard c) {
        canvas.drawBitmap(c.bitmap, c.x, 0f, paint);
    }

    private void drawDroidCard(Canvas canvas, int index) {
        DMLog.e(this.getClass().getCanonicalName(), "after  drawDroidCard");
        canvas.save();
        DroidCard card = mDroidCards.get(index);
        DroidCard nextCard = mDroidCards.get(index + 1);
        canvas.clipRect(new Rect(0, 0, nextCard.x, card.height));
        canvas.drawBitmap(card.bitmap, card.x, 0f, paint);
        canvas.restore();
    }
}
